$(function() {
	/*
	 * 初始化 select
	 */
	$('select').select2();

	/*
	 * 初始化编辑器
	 */
	var newsEditor = CKEDITOR
			.replace(
					'news-editor',
					{
						language : 'zh-cn',
						toolbar : 'Basic',
						height : 480,
						uiColor : '#FFFFFF',
						extraPlugins : 'uploadimage',
						uploadUrl : '/base/upload/uploadFile',
						filebrowserUploadUrl : '/base/upload/uploadFile',
						toolbarGroups : [
								{
									name : 'document',
									groups : [ 'mode', 'document', 'doctools' ]
								},
								{
									name : 'clipboard',
									groups : [ 'clipboard', 'undo' ]
								},
								{
									name : 'editing',
									groups : [ 'find', 'selection',
											'spellchecker', 'editing' ]
								},
								{
									name : 'forms',
									groups : [ 'forms' ]
								},
								{
									name : 'basicstyles',
									groups : [ 'basicstyles', 'cleanup' ]
								},
								{
									name : 'paragraph',
									groups : [ 'list', 'indent', 'blocks',
											'align', 'bidi', 'paragraph' ]
								}, {
									name : 'links',
									groups : [ 'links' ]
								}, {
									name : 'insert',
									groups : [ 'insert' ]
								}, {
									name : 'styles',
									groups : [ 'styles' ]
								}, {
									name : 'colors',
									groups : [ 'colors' ]
								}, {
									name : 'tools',
									groups : [ 'tools' ]
								}, {
									name : 'others',
									groups : [ 'others' ]
								}, {
									name : 'about',
									groups : [ 'about' ]
								} ],
						removeButtons : 'Table,Flash,Image,Save,NewPage,Templates,Cut,Copy,Paste,Find,Replace,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Iframe,About'
					});

	newsEditor
			.on(
					'fileUploadRequest',
					function(evt) {
						var fileLoader = evt.data.fileLoader, formData = new FormData(), xhr = fileLoader.xhr;
						xhr.open('POST', fileLoader.uploadUrl, true);
						formData.append('file', fileLoader.file,
								fileLoader.fileName);
						fileLoader.xhr.send(formData);
						evt.stop();
					}, null, null, 6);

	newsEditor.on('fileUploadResponse', function(evt) {
		console.log(evt.data);
		var resData = JSON.parse(evt.data.fileLoader.xhr.response);
		evt.stop();
		// Ger XHR and response.
		var data = evt.data;
		if (resData.errorCode == 1) {
			// Error occurred during upload.
			data.message = resData.msg;
			evt.cancel();
		} else {
			data.message = resData.msg;
			data.url = resData.data;
		}
	});

	newsEditor.on('change', function(evt) {
		console.log(newsEditor.getData().length);
	});

	/*
	 * 初始化消息弹窗
	 */
	$('#msg-modal,#pic-modal').modal({
		backdrop : 'static',
		keyboard : false,
		show : false
	});

	/*
	 * 表单验证错误 显示/隐藏
	 */
	function toggleError(show, ele, msg) {
		if (ele.next().length == 0) {
			ele
					.after('<label class="err-label"><i class="fa fa-times-circle-o"></i><span></span></label>');
		}
		if (show) {
			ele.next().show().find('span').html(msg);
			ele.parent().addClass('has-error');
		} else {
			ele.parent().removeClass('has-error');
			ele.next().hide();
		}
	}

	/*
	 * 初始化图片上传按钮
	 */
	var $coverUploading = $('#cover-upload-box .overlay').hide();

	$('.thumbnail').on('click', function() {
		$('#image').click();
	});

	$('#image').on(
			'change',
			function() {
				var picFormData = new FormData();
				picFormData.append('file', this.files[0]);
				$coverUploading.show();
				$.ajax({
					url : '/upload/uploadFile',
					type : 'post',
					data : picFormData,
					dataType : 'json',
					cache : false,
					contentType : false,
					processData : false,
					success : function(obj) {
						if (obj.errorCode == 0) {
							$coverUploading.hide();
							$('.thumbnail').css('background-image',
									'url(' + obj.data + ')');
						} else {
						}
					}
				});
			});

	/*
	 * 保存资讯
	 */
	function save() {

		var formData = {};
		var url = $('input[name="id"]').length > 0 ? '/web/news/edit'
				: '/web/news/add';
		$('#news-editor').val(newsEditor.getData());
		$('#news-form :input').each(function() {
			formData[$(this).attr('name')] = $(this).val();
		});
		// formData['isPublished'] = 1;
		formData['categoryId'] = $(".form-control.select2").val();
		if(formData['image'].length==0||formData['image']==""){
			greeting({msg:"请先上传主题图"});
			return false;
		}
		cAjax({
			url : url,
			data : formData,
			dataType : 'json',
			cache : false,
			success : function(obj) {
//				$('#msg-modal').modal('show');
				$('#msg-modal').val();
				location.href = '/web/news/list';
			}
		});
	}

	/*
	 * 初始化表单验证
	 */
	$('#news-form').validate({
		rules : {
			title : "required",
			publisher : "required",
			sourceFrom : "required",
			image : "required",
		},
		showErrors : function(errorMap, errorList) {
			if (errorList.length == 0) {
				return;
			} else {
				var msg = '', curEle;
				if (errorList.length > 0) {
					var err = errorList[0], curEle = $(err.element);
					if (err.method == 'required') {
						msg = curEle.prev().html() + "不能为空";
					}
				}
				toggleError(true, curEle, msg);
			}
		},
		submitHandler : function() {
			save();
		},
		onkeyup : function(ele) {
			toggleError(false, $(ele));
		}
	});

	var picUploader = new PicUploader({
		success: function(obj) {
			var $thumb = $('.thumbnail');
			var imageUrl = obj['data'];
			$thumb.css('background-image','url('+imageUrl+')');
			$thumb.siblings('input').val(imageUrl);
		}
	});
	$('.thumbnail').on('click',function(){
		picUploader.start();
	});

	$('#news-save-btn').on('click', function() {
		if($('input[name="id"]').length==0){
			$('#isPublished').val(0);
		}
		$('#news-form').submit();
	});

	$('#news-pub-btn').on('click', function() {
		$('#isPublished').val(1);
		$('#news-form').submit();
	})
	
});

